package com.gy.feign.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

@Configuration
public class FeignConfig implements RequestInterceptor {
    /**
     * 复写feign请求对象
     *
     * @param requestTemplate hhh
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == attributes) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (null == headerNames) {
            return;
        }
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String values = request.getHeader(name);
            // 跳过 content-length
            if (name.equals("content-length")) {
                continue;
            }
            requestTemplate.header(name, values);
        }
    }

//    @Override
//    public void apply(RequestTemplate requestTemplate) {
//        //获取请求头
//        Map<String, String> headers = getHeaders(Objects.requireNonNull(getHttpServletRequest()));
//        for (Map.Entry<String, String> entry : headers.entrySet()) {
//            if (!"content-length".equalsIgnoreCase(entry.getKey())) {
//                requestTemplate.header(entry.getKey(), entry.getValue());
//            }
//        }
//    }

    //获取请求对象
    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //拿到请求头信息
    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

}
